﻿using System;
using System.Collections.Generic;
using WindowServices.Common;

namespace WindowServices.Interface
{
    /// <summary>
    /// 
    /// </summary>
    public class NameValueHelper
    {
        private NameValueHelper()
        {
        }


        private static string _configfile = string.Format("{0}\\AppSetting.config", AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'));
        private const string RootPath = "/configuration/Settings";

        private const string ServicePath = RootPath + "/Setting";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strPath"></param>
        public static void SetConfigBasePath(string strPath)
        {
            _configfile = string.Format("{0}\\AppSetting.config", strPath.TrimEnd('\\'));
        }
        private static ConfigHelper CreateNameValueHelper()
        {
            return new ConfigHelper(_configfile);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dictionary"></param>
        public static void Update(Dictionary<string, string> dictionary)
        {
            using (var helper = CreateNameValueHelper())
            {
                var dic = new Dictionary<string, string>();
                foreach (var key in dictionary.Keys)
                {
                    helper.DelNode(string.Format("{0}[@key=\"{1}\"]", ServicePath, key));
                    dic.Clear();
                    dic.Add("key", key);
                    dic.Add("value", dictionary[key]);
                    helper.AddNode(RootPath, "Setting", dic, "");
                }

                helper.Save();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            using (var helper = CreateNameValueHelper())
            {
                return helper.GetAttribeOrDefault(string.Format("{0}[@key=\"{1}\"]", ServicePath, key), "value");
            }
        }
    }
}
